﻿
using System;
using System.ServiceModel;

using WSU.Cheka.HelloWCF.Contracts;

namespace WSU.Cheka.HelloWCF.Client
{
    sealed class MultiContractClient : IDisposable, IHelloWCF, IWsuContract
    {
        #region "member variables"
        private HelloWcfClient m_helloClient;
        private WsuClient m_wsuClient;
        #endregion

        #region "constructor and destructor"
        public MultiContractClient(string helloEndCfg, string wsuEndCfg)
        {
            m_helloClient = new HelloWcfClient(helloEndCfg);
            m_wsuClient = new WsuClient(wsuEndCfg);
        }

        private void CloseProxy(ICommunicationObject proxy)
        {
            if (proxy.State == CommunicationState.Faulted)
                proxy.Abort();
            else
                proxy.Close(); // if already Faulted, "Close" will throw out exception
        }

        public void Dispose()
        {
            CloseProxy(m_helloClient);
            CloseProxy(m_wsuClient);
        }

        #endregion

        #region "implement IHelloWCF"
        public string Hello(string content)
        {
            return m_helloClient.Hello(content);
        }

        public float Add(float x, float y)
        {
            return m_helloClient.Add(x, y);
        }
        #endregion

        #region "implement IWsuContract"

        public string[] GetDepartments()
        {
            return m_wsuClient.GetDepartments();
        }

        public int GetNumberByDepartment(string departName)
        {
            return m_wsuClient.GetNumberByDepartment(departName);
        }

        public void AddDepartment(string departName, int number)
        {
            m_wsuClient.AddDepartment(departName, number);
        }

        #endregion

        #region "static entry"

        public static void TestMain()
        {
            using (MultiContractClient clientProxy = new MultiContractClient("multiHello", "multiWsu"))
            {
                // ------------------------- test hello service
                Console.WriteLine(clientProxy.Hello("using multiple contracts"));
                Console.WriteLine("add result = {0}\n", clientProxy.Add(1.23f, 3.14f));

                // ------------------------- test wsu service
                Console.WriteLine("Original Departments and Numbers:");
                ((IWsuContract)clientProxy).Invoke();

                // below test demonstrate the effect "session transmission channel + PerSession service instance"
                clientProxy.AddDepartment("NewDepartment", 50);

                Console.WriteLine("\nAfter adding new, New Departments and Numbers: ");
                ((IWsuContract)clientProxy).Invoke();
            }
        }

        #endregion
    }
}